#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/3/17 10:56
# @Author  : Wang Yuhang
# @File    : views.py
# @Func    : auth蓝本中的路由和视图函数

from flask import render_template, redirect, request, url_for, flash
from flask_login import login_user, logout_user, login_required, current_user
from . import auth
from ..models import User, db
from .forms import LoginForm, RegistrationForm
from ..email import send_email


@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user is not None and user.verify_password(form.password.data):
            login_user(user, form.remember_me.data)
            return redirect(request.args.get('next') or url_for('main.index'))
        flash('无效的用户名或者密码！')
    return render_template('auth/login.html', form=form)


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    flash('当前登录已经注销！')
    return redirect(url_for('main.index'))


@auth.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(email=form.email.data,
                    username=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()  # 确认令牌需要用到id，提交数据库后才会生成id
        token = user.generate_confirmation_token()
        send_email(user.email, '确认您的注册账户', 'auth/email/confirm', user=user, token=token)
        flash('注册确认邮件已发送到您的邮件，请查收！')
        return redirect(url_for('auth.login'))
    return render_template('auth/register.html', form=form)


@auth.route('/confirm/<token>')
@login_required
def confirm(token):
    if current_user.confirmed:                  # 目前用户已认证
        return redirect(url_for('main.index'))
    if current_user.confirm(token):             # 用户验证成功
        flash('您的账户已验证，欢迎！')
    else:
        flash('邮件中的验证链接已过期！')
    return redirect(url_for('main.index'))


@auth.before_app_request
def before_request():
    if current_user.is_authenticated:
        current_user.ping()                 # 更新已登录用户的访问时间
        if not current_user.confirmed \
            and request.endpoint[:5] != 'auth.' \
            and request.endpoint != 'static':
            return redirect(url_for('auth.unconfirmed'))


@auth.route('/unconfirmed')
def unconfirmed():
    if current_user.is_anonymous or current_user.confirmed:
        return redirect(url_for('main.index'))
    return render_template('auth/unconfirmed.html')


@auth.route('/confirm')
@login_required
def resend_confirmation():
    token = current_user.generate_confirmation_token()
    send_email(current_user.email, '确认您的注册账户', 'auth/email/confirm', user=current_user, token=token)
    flash("一封新的确认邮件已经发送到您的邮箱，请查收！")
    return redirect(url_for('main.index'))






